package Cn.edu.zafu.bigdata.x.cxy;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

public class StudentInfoSystem {

    private static final String FILE_NAME = "students.data";
    private List<Student> students;

    public StudentInfoSystem() {
        students = new ArrayList<>();
        loadStudents();
    }

    public static void main(String[] args) {
        StudentInfoSystem system = new StudentInfoSystem();
        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("======= 学生信息管理系统 =======");
            System.out.println("1. 添加学生信息");
            System.out.println("2. 检索学生信息");
            System.out.println("3. 更新学生信息");
            System.out.println("4. 删除学生信息");
            System.out.println("5. 退出程序");
            System.out.print("请输入操作编号 (1-5): ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // Consume newline

            switch (choice) {
                case 1:
                    system.addStudent(scanner);
                    break;
                case 2:
                    system.searchStudent(scanner);
                    break;
                case 3:
                    system.updateStudent(scanner);
                    break;
                case 4:
                    system.deleteStudent(scanner);
                    break;
                case 5:
                    system.saveStudents();
                    System.out.println("程序已退出。");
                    scanner.close();
                    return;
                default:
                    System.out.println("无效的选项，请重新输入。");
            }
        }
    }

    private void loadStudents() {
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_NAME))) {
            students = (List<Student>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            System.out.println("文件读取错误，将创建新文件。");
        }
    }

    private void saveStudents() {
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME))) {
            oos.writeObject(students);
        } catch (IOException e) {
            System.out.println("文件保存错误。");
        }
    }

    private void addStudent(Scanner scanner) {
        while (true) {
            System.out.print("请输入学号: ");
            String id = scanner.nextLine();
            boolean idExists = students.stream().anyMatch(s -> s.getId().equals(id));
            if (idExists) {
                System.out.println("学号重复，请重新输入。");
            } else {
                System.out.print("请输入姓名: ");
                String name = scanner.nextLine();
                System.out.print("请输入电话: ");
                String phone = scanner.nextLine();

                Student student = new Student(id, name, phone);
                students.add(student);
                System.out.println("学生信息已添加。");
                break; // 退出循环
            }
        }
    }

    private void searchStudent(Scanner scanner) {
        while (true) {
            System.out.print("请输入学号进行检索（输入'QUIT'退出）: ");
            String id = scanner.nextLine();
            if ("QUIT".equalsIgnoreCase(id)) {
                break;
            }

            Optional<Student> studentOptional = students.stream()
                    .filter(s -> s.getId().equals(id))
                    .findFirst();

            if (studentOptional.isPresent()) {
                System.out.println("找到学生：" + studentOptional.get());
            } else {
                System.out.println("未找到该学生。");
            }
        }
    }

    private void updateStudent(Scanner scanner) {
        while (true) {
            System.out.print("请输入学号进行更新（输入'QUIT'退出）: ");
            String id = scanner.nextLine();
            if ("QUIT".equalsIgnoreCase(id)) {
                break;
            }

            Student student = students.stream()
                    .filter(s -> s.getId().equals(id))
                    .findFirst()
                    .orElse(null);

            if (student != null) {
                System.out.print("请输入新姓名: ");
                String name = scanner.nextLine();
                System.out.print("请输入新电话: ");
                String phone = scanner.nextLine();
                student.setName(name);
                student.setPhone(phone);
                System.out.println("学生信息已更新。");
            } else {
                System.out.println("未找到该学生。");
            }
        }
    }

    private void deleteStudent(Scanner scanner) {
        while (true) {
            System.out.print("请输入学号进行删除（输入'QUIT'退出）: ");
            String id = scanner.nextLine();
            if ("QUIT".equalsIgnoreCase(id)) {
                break;
            }

            boolean removed = students.removeIf(s -> s.getId().equals(id));
            if (removed) {
                System.out.println("学生信息已删除。");
            } else {
                System.out.println("未找到该学生。");
            }
        }
    }
}

class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    private String id;
    private String name;
    private String phone;

    public Student(String id, String name, String phone) {
        this.id = id;
        this.name = name;
        this.phone = phone;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}